var mongoose = require('mongoose'),
    Promise  = require('bluebird');
    Weixinuser = require('../models/weixinuser');

exports.add    = function (registerData) {
  return new Promise(function (resolve, reject) {
    new Weixinuser(registerData).save(function (err, user) {
      if (err) {
        reject(err);
      } else {
        resolve(user);
      }
    });
  });
};

/**
 * 根据openid逻辑删除用户 ： invalid_flag: 1
 * @param {String} openid weixin Openid
 * @returns Promise
 */
exports.logicDeleteByOpenId = function (openid) {
  return new Promise(function (resolve, reject) {
    Weixinuser.update({'openid': openid}, {invalid_flag: 1}, function (err, numAffected) {
        if (err) {
          reject({ok:0, error: err});
        } else {
          resolve({ok: 1, n: numAffected});
        }
      });
  });
};

/**
 * 删除所有给定openid的记录
 * @param {String} openid 微信openid
 * @returns Promise
 */
exports.deleteByOpenId = function (openid) {
  return new Promise(function (resolve, reject) {
    Weixinuser.remove({'openid': openid}, function (err, n) {
      console.log(n.result);
    });
  });
};

exports.update = function (id, doc) {
  //delete doc._id;
  return new Promise(function (resolve, reject) {
    Weixinuser.update({'_id': id}, doc, function (err, product) {
      if (err) {
        reject(err);
      } else {
        resolve(product);
      }
    });
  });
};

/**
 * 根据条件检索， 如果有数据则更新之， 无则插入(包含schema中定义的含有默认值的字段)
 * @param {Object} selector 查询条件
 * @param {Object} doc 数据
 * @returns Promise
 */
exports.upsert = function (selector, doc) {
  var query = Weixinuser
    .update.call(Weixinuser, selector, doc, {upsert: true, setDefaultsOnInsert: true});
  return query.exec();
};

/**
 * 按条件查找, 如果有则更新, 无则插入(包含schema中定义的含有默认值的字段)
 * 注意:
 * 1. 最后的`.exec()`, 按照mongoose官方文档的说法: `.exec()` gives you a fully-fledged promise
 * 2. 使用call绑定上下文为schema
 * @param condition 查询条件
 * @param update 需要更新的document
 * @returns Promise|Array|{index: number, input: string} 包含更新或插入的文档
 */
exports.findOneAndUpdate = function (condition, update, callback) {
  var options =  {"upsert": true, "new": true, setDefaultsOnInsert: true};

  // 有回调函数时, 将不在返回Promise, 返回undefined
  if ('function' === typeof callback) {
    return Weixinuser.findOneAndUpdate
      .call(Weixinuser, condition, update, options, callback);
  } else {
    return Weixinuser.findOneAndUpdate
      .call(Weixinuser, condition, update, options).exec();
  }
};

exports.findOne = function (condition) {
  return Weixinuser.findOne.call(Weixinuser, condition).exec();
};

exports.findByOpenId = function (openid) {
  return new Promise(function (resolve, reject) {
    Weixinuser.findOne({'openid': openid}, function (err, user) {
      if (err) {
        reject(err);
      } else {
        resolve(user);
      }
    });
  });
};

exports.findAll = function () {
  return new Promise(function (resolve, reject) {
    Weixinuser.find({'invalid_flag': 0}, function (err, user) {
      if (err) {
        reject(err);
      } else {
        resolve(user);
      }
    });
  });
};

exports.findOneByEmail = function (email) {
    return Weixinuser.findOne.call(Weixinuser, {email: email}).exec();
};